from app02 import models
from django import forms

from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from app02.utils.bootstrap import BootStrapModelForm

class UserModelForm(BootStrapModelForm):
    name = forms.CharField(min_length=3, label="用户名1")
    password = forms.CharField(min_length=3, label="密码1")

    class Meta:
        model = models.userinfo
        fields = ["name", "password", "age", "account",
                  "create_time", "gender", "depart"]

        # widgets={
        #     "name":forms.TextInput(attrs={"class":"form-control"}),
        #     "password":forms.PasswordInput(attrs={"class":"form-control"}),
        #     "age":forms.TextInput(attrs={"class":"form-control"}),
        # }


class PrettyModelForm(BootStrapModelForm):
    # 验证：方法1
    mobile = forms.CharField(
        label="手机号1",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')],
    )

    class Meta:
        model = models.prettynum
        fields = ["mobile", "price", "level", "status"]
        # fields = "__all__"   所有字段
        # exclude = ["level"]  排除level字段

    # 验证：方法2  复杂验证使用钩子函数  以clean_字段名
    def clean_mobile(self):
        # 当前编辑的那一行的id self.instance.pk
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.prettynum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()

        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过，用户输入的值返回
        return txt_mobile

